<template>
    <el-dialog v-model="visible" title="素材识别编排" width="500px" :close-on-click-modal="false">
            <el-form :model="formData" ref="formRef" :rules="formRules" label-width="80px" v-loading="submitLoading">
                <el-form-item label="关键词:" prop="keyword">
                    <el-input v-model="formData.keyword" placeholder="请输入关键词" clearable />
                </el-form-item>
                <el-form-item label="地区:" prop="area">
                    <el-select v-model="formData.area" placeholder="请选择地区" style="width: 100%;" clearable>
                        <el-option v-for="item in countryOptions" :key="item.label" :label="item.label"
                            :value="item.label" />
                    </el-select>
                </el-form-item>
                <el-form-item label="出词数:" prop="wordNum">
                    <el-input-number v-model="formData.wordNum" :min="1" :max="10" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">提交</el-button>
                </div>
            </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import service from '../config';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { countryOptions } from '../tool';
import axios from 'axios';
import { useAuthStore } from '../store/auth';

const authStore = useAuthStore()

const visible = defineModel<boolean>('visible', { default: false })
const emit = defineEmits(['success'])

const submitLoading = ref(false)
const formRef = ref<FormInstance>()
const formData = reactive({
    keyword: '',
    area: '',
    wordNum: 1
})

// 表单验证规则
const formRules = reactive<FormRules>({
    keyword: [
        { required: true, message: '请输入关键词', trigger: 'blur' }
    ],
    area: [
        { required: true, message: '请选择地区', trigger: 'change' }
    ],
    wordNum: [
        { required: true, message: '请选择出词数', trigger: 'change' }
    ]
})

const handleCancel = () => {
    visible.value = false
}


const handleSubmit = async () => { 
    if (!formRef.value) return
    if (submitLoading.value) return
    try {
        submitLoading.value = true
        const valid = await formRef.value.validate()
        if (!valid) return
        const res = await service.post('/materialRecord/add', {
            keyword: formData.keyword,
            area: formData.area,
            wordNum: formData.wordNum,
            isAuto: true
        })

        const webhookUrl = import.meta.env.PROD
            ? 'https://pixeljet-n8n.com/webhook/0af289d6-9a61-414d-81bb-a5bad02720ee'
            : '/wkfapi/webhook/0af289d6-9a61-414d-81bb-a5bad02720ee'
        const payload: any = {
            keyword: formData.keyword,
            area: formData.area,
            num: formData.wordNum,
            arrange_id: res?.data,
            created_user_id: authStore?.userId,
            devModel: import.meta.env.MODE !== 'production' ? 'test' : 'official'
        }
        await axios.post(webhookUrl, payload)
        ElMessage.success('提交成功')
        visible.value = false
        emit('success')
    } catch (error: any) {
        if (error?.response?.data?.message) {
            ElMessage.error(error.response.data.message)
        } else if (error?.message && !error.message.includes('validate')) {
            ElMessage.error(error.message)
        }
    } finally {
        submitLoading.value = false
    }
}

// 重置表单
const resetForm = () => {
    formData.keyword = ''
    formData.area = ''
    formData.wordNum = 1
    formRef.value?.clearValidate()
}

defineExpose({
    resetForm
})
</script>

<style scoped></style>
